package com.my.springbootkafka;

import com.my.springbootkafka.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.my.springbootkafka.Constants.*;

/**
 * @author: marshal
 * @date: 2023-05-12 2:35 PM
 */
@Component
@Slf4j
public class KafkaService {

    @KafkaListener(topics = USER_TOPIC, groupId = USER_GROUP)
    public void listen(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
        Optional<?> message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            if (topic.equals(USER_TOPIC)) {
//                User user = (User) message.get();
                Object user =  message.get();
                log.info("消费了: topic: {} , message : {}", USER_TOPIC, user);
            }
            ack.acknowledge();
        } else {
            log.debug("消息为空");
        }
    }
}
